package com.leyou.user.service;

import com.leyou.common.constants.MQConstants;
import com.leyou.common.constants.RegexPatterns;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private static final String key_prefix = "verify:code:phone:";

    public Boolean checkData(String data, Integer type) {
         //判断是哪个字段
        User user = new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //判断是否唯一
        int count = userMapper.selectCount(user);
        //count==1有则为不可用，没有为可用
        return count==0;
    }

    /**
     * 接收手机号，产生验证码，利用MQ把消息发送到ly-sms,保存验证码到redis中
     * @param phone
     */
    public void sendVerifyCode(String phone) {
        //1.验证手机号码
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        //2.手机号码没问题，产生验证码6位的
        String code = RandomStringUtils.randomNumeric(6);
        //3.利用mq把消息发送到ly-sms中
        redisTemplate.opsForValue().set(key_prefix+phone,code,5, TimeUnit.MINUTES);
        //4.把消息发送到ly-sms中，来发送验证码给客户
        Map<String,String> map = new HashMap<>(16);
        map.put("phone",phone);
        map.put("code",code);
        amqpTemplate.convertAndSend(MQConstants.Exchange.SMS_EXCHANGE_NAME,MQConstants.RoutingKey.VERIFY_CODE_KEY,map);
    }

    public void userRegister(User user, String code) {
        //1.校验短信验证码和信息
        String key = key_prefix+user.getPhone();
        String cacheCode = redisTemplate.opsForValue().get(key);
        if (!code.equals(cacheCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
        //2.对密码加密
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        //3.写入数据库
        int count = userMapper.insertSelective(user);
        if (count!=1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public UserDTO queryUserByUsernameAndPassword(String username, String password) {
        //1.根据用户名查询
        User u = new User();
        u.setUsername(username);
        User user = userMapper.selectOne(u);
        //2.判断是否存在
        if (user == null) {
            //用户名错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //3.校验密码
        if (!bCryptPasswordEncoder.matches(password,user.getPassword())){
            //密码错误
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        return BeanHelper.copyProperties(user,UserDTO.class);
    }
}